package com.example.opcdemo.opc.config;


import com.example.opcdemo.opc.BizOpcInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.sdk.client.api.UaClient;
import org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider;
import org.eclipse.milo.opcua.sdk.client.model.nodes.objects.ServerTypeNode;
import org.eclipse.milo.opcua.sdk.client.nodes.UaNode;
import org.eclipse.milo.opcua.stack.core.Identifiers;
import org.eclipse.milo.opcua.stack.core.security.SecurityPolicy;
import org.eclipse.milo.opcua.stack.core.types.builtin.*;
import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger;
import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned;
import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ykz
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class OpcUaConfig {
    public static UaClient opcLink = null;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * opc ua  打开连接订阅
     * res  是否需要重复连接
     *
     * @throws Exception
     */
    public void createSubscription(BizOpcInfo info, boolean res) {
        try {
            //等待三秒(可要可不要)
//            Thread.sleep(3 * 1000);
            UaClient uaClient = null;

            Path securityTempDir = Paths.get(System.getProperty("java.io.tmpdir"), "security");
            Files.createDirectories(securityTempDir);
            if (!Files.exists(securityTempDir)) {
                throw new Exception("unable to create security dir: " + securityTempDir);
            }
            OpcUaClient opcClient =  OpcUaClient.create(info.getOpcUrl(),
                    endpoints ->
                            endpoints.stream().filter(e -> e.getSecurityPolicyUri().equals(SecurityPolicy.None.getUri())).findFirst(),
                    configBuilder ->
                            configBuilder
                                    .setApplicationName(LocalizedText.english("eclipse milo opc-ua client"))
                                    .setApplicationUri("urn:eclipse:milo:examples:client")
                                    //访问方式
                                    .setIdentityProvider(new AnonymousProvider())
                                    .setRequestTimeout(UInteger.valueOf(50000))
                                    .build()
            );
            uaClient = opcClient.connect().get();
            if (opcLink == null){
                opcLink = uaClient;
            }else {
                uaClient.disconnect().get();
            }
            log.info("opc链接成功");
        } catch (Exception e) {
//            if (res) {
//                //重复连接
//                createSubscription(info,true);
//            } else {
//            }
            e.printStackTrace();
            log.info("opc链接失败 {}", e.getMessage());

        }
    }

}